|
The wildcard ? in Java is a special actual parameter for the instantiation of generic (parameterized) types. It can be used for the instantiation, not in the definition of a generic unit. Thus, a wildcard is a form of ''use-site'' variance annotation (contrast this with the ''definition-site'' variance annotations found in C# and Scala). This article summarizes the most important rules for its use.== Covariance for generic types == Unlike arrays (which are covariant in Java), different instantiations of a generic type are not compatible with each other, not even explicitly: With the declaration Generic the compiler would report a conversion error for both castings (Generic and (Generic .This incompatibility may be softened by the wildcard if ? is used as an actual type parameter: Generic> is the abstract supertype for all instantiations of the generic type. It means, no objects of this type may be created, only variables. The usage of such a variable is to refer to instantiations of Generic with any actual type parameter.== Wildcard as parameter type == In the body of a generic unit, the (formal) type parameter is handled like its upper bound (expressed with extends ; Object if not constrained). If the return type of a method is the type parameter, the result (e.g. of type ? ) can be referenced by a variable of the type of the upper bound (or Object ). In the other direction, the wildcard fits no other type, not even Object : If ? has been applied as the formal type parameter of a method, no actual parameters can be passed to it. It can be called only by casting the wildcard reference:抄文引用元・出典: フリー百科事典『 ウィキペディア(Wikipedia)』 ■ウィキペディアで「Wildcard (Java)」の詳細全文を読む スポンサード リンク
|